const express = require('express');
const GlobalUtil = require('../Util/GlobalUtil');
const bodyParser = require('body-parser');
const router = express.Router();

router.use(bodyParser.json());
router.use(bodyParser.text());

//获取公告
router.get('/getNotice', async (req, res) => {
    try {
        //获取数据库中最新的一条数据（id最大）作为要显示的公告
        const sql = 'SELECT * FROM notice ORDER BY id DESC LIMIT 2';
        const result = await GlobalUtil.asyncQuery(sql);
        if (result.length > 0) {
            const date = new Date(result[0].release_time);
            //当前事件大于发布时间则发布新公告，否则发布老公告;
            if (date < new Date()) {
                const data = {
                    msg: "new notice",
                    id: result[0].id,
                    content: result[0].content,
                }
                res.send(data);
            } else {
                //最新公告未到发布时间则继续发布老公告
                //确保查询出的公告数大于等于2
                if (result.length >= 2) {
                    const data = {
                        msg: "old notice",
                        id: result[1].id,
                        content: result[1].content,
                    }
                    res.send(data);
                } else {
                    res.send({ msg: "暂无公告"});
                }
            }
        } else {
            res.send({ msg: "暂无公告"});
        }
    } catch (error) {
        console.error(error);
        res.status(500).send("Database error");
    }
})

module.exports = router;

